using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Net.NetworkInformation;
using System.IO;

namespace PortChecker
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void PortTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 只允许输入数字
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void CheckButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(PortTextBox.Text))
            {
                MessageBox.Show("请输入端口号！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            int port;
            if (!int.TryParse(PortTextBox.Text, out port) || port < 1 || port > 65535)
            {
                MessageBox.Show("请输入有效的端口号（1-65535）！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            CheckPort(port);
        }

        private void CheckPort(int port)
        {
            try
            {
                var processes = new List<ProcessInfo>();
                // 使用 netstat 命令获取端口对应的进程ID
                var psi = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c netstat -ano | findstr :{port}",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
                using (var process = Process.Start(psi))
                {
                    string output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();
                    var lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    var pids = new HashSet<int>();
                    foreach (var line in lines)
                    {
                        var parts = Regex.Split(line.Trim(), "\\s+");
                        if (parts.Length >= 5)
                        {
                            int pid;
                            if (int.TryParse(parts[4], out pid))
                            {
                                pids.Add(pid);
                            }
                        }
                    }
                    foreach (var pid in pids)
                    {
                        try
                        {
                            var proc = Process.GetProcessById(pid);
                            processes.Add(new ProcessInfo
                            {
                                Id = proc.Id,
                                Name = proc.ProcessName,
                                Port = port
                            });
                        }
                        catch { }
                    }
                }
                ProcessGrid.ItemsSource = processes;
                if (!processes.Any())
                {
                    MessageBox.Show($"端口 {port} 未被占用", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"检查端口时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void KillProcess_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var processInfo = button.DataContext as ProcessInfo;

            if (processInfo != null)
            {
                try
                {
                    var process = Process.GetProcessById(processInfo.Id);
                    var result = MessageBox.Show(
                        $"确定要结束进程 {processInfo.Name} (PID: {processInfo.Id}) 吗？",
                        "确认",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        process.Kill();
                        process.WaitForExit();
                        CheckPort(processInfo.Port); // 刷新列表
                        MessageBox.Show("进程已成功结束！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"结束进程时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
    }

    public class ProcessInfo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Port { get; set; }
    }
} 